var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(3000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.on('connection', function (socket) {
  console.log(socket.id)

  socket.emit('welcome', {
    type: 'notice',
    id: '',
    msg: 'Welcome'
  });

  socket.on('post', function (msg) {
    let param = {
      id: socket.id,
      msg
    }
    console.log('post: ', io);
    io.emit('message', param)
  });

  // 断开事件
  socket.on('disconnect', function () {
    socket.emit('disconnected');
  });
});

console.log('App started at: 3000')
